let express = require('express')
let router = express.Router() 
let multiparty = require('multiparty')
const { v4: uuidv4 } = require('uuid');
let path = require('path')
let fs = require('fs')

// 处理文件上传的路由
// 设置上传文件的保存目录
const uploadDir = path.join(__dirname, 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// 处理文件上传的路由
router.post('/uploads', (req, res) => {
  // 创建一个 multiparty 表单对象
  const form = new multiparty.Form({ uploadDir: uploadDir });

  // 解析表单数据
  form.parse(req, (err, fields, files) => {
    if (err) {
      console.error(err);
      return res.status(500).send({ error: 'File upload failed.' });
    }

    // 文件上传成功后的处理
    const uploadedFiles = files['file']; // 'file' 是上传文件的字段名
    if (!uploadedFiles || uploadedFiles.length === 0) {
      return res.status(400).send({ error: 'No files uploaded.' });
    }

    // 移动上传的文件到指定目录
    const uploadedFilePaths = [];
    uploadedFiles.forEach(file => {
      const uniqueId = uuidv4(); // 使用 UUID 生成唯一标识符
      const uniqueFilename = uniqueId + path.extname(file.originalFilename);
      const filePath = path.join(uploadDir, uniqueFilename);
      fs.renameSync(file.path, filePath);
      uploadedFilePaths.push(filePath);
    });

    res.send({ files: uploadedFilePaths });
  });
});

module.exports = router;

